package com.ams.common.base.result;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.io.Serializable;

/**
 * @Author yuanss
 * @Date 2024/1/27 15:12
 * @Description: 通用结果返回类
 * @Version 1.0
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class R<T> implements Serializable {
    private String code;
    private T data;
    private String msg;
    private Integer total;

    public static <T> R<T> ok() {
        return ok(null);
    }

    public static <T> R<T> ok(T data) {
        ResultCode rce = ResultCode.SUCCESS;
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            rce = ResultCode.SYSTEM_EXECUTION_ERROR;
        }
        return result(rce, data);
    }

    public static <T> R<T> ok(T data, Long total) {
        R<T> result = new R<>();
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg(ResultCode.SUCCESS.getMsg());
        result.setData(data);
        result.setTotal(total.intValue());
        return result;
    }

    private static <T> R<T> result(ResultCode rce, T data) {
        return new R<T>(rce.getCode(), data, rce.getMsg());
    }

    public R(String code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
    }
    public R() {}

    public static <T> R<T> failed(ResultCode resultCode) {
        return new R<>(resultCode.getCode(), null, resultCode.getMsg());
    }

    public static <T> R<T> failed(String msg) {
        return new R<>(ResultCode.SYSTEM_EXECUTION_ERROR.getCode(), null, msg);
    }
}
